//
//  ViewConfigManager.swift
//  MYModule
//
//  Created by 李然 on 2022/7/19.
//

import Foundation

class ViewConfigManager{
    
    static let shared = ViewConfigManager()
    
    private var cacheTable = [String:[ViewAttribute]]()
    
    func getViewAttribetes(by page_name:String) -> [ViewAttribute]{
        if cacheTable[page_name] == nil{
            try? self.cachePageConfig(page_name)
        }
        return cacheTable[page_name] ?? []
    }
    
    func getViewAttribete(by page_name:String, widgetId:String) -> ViewAttribute?{
        return getViewAttribetes(by: page_name).first(where: {$0.widget_id == widgetId})
    }
    
    private func cachePageConfig(_ page_name:String) throws -> Bool {
        if let _ = cacheTable[page_name]{
            return true
        }
        guard let path = Bundle.main.path(forResource: page_name, ofType: "json") else {
            return false
        }
        let data = try Data.init(contentsOf: URL(fileURLWithPath: path))
        
        var attrArry = [ViewAttribute]()
        if let array = try JSONSerialization.jsonObject(with:data) as? NSArray{
            for i in array {
                if let item = i as? [String:Any]{
                    var attr = ViewAttribute()
                    attr.widget_id = item["widget_id"] as? String ?? ""
                    attr.back_color = item["back_color"] as? String
                    attr.text_color = item["text_color"] as? String
                    attr.text_size = item["text_size"] as? CGFloat
                    attr.selected_color = item["selected_color"] as? String
                    attr.font_name = item["font_name"] as? String
                    attr.corner_size = item["corner_size"] as? CGFloat
                    attr.image_name = item["image_name"] as? String
                    attr.is_show_shadow = item["is_show_shadow"] as? Int
                    attrArry.append(attr)
                }
            }
        }
        self.cacheTable[page_name] = attrArry
        return true
    }
}
